package com.example.timeplanning_teacher;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import org.jetbrains.annotations.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class FragmentMakeRules extends Fragment {

    private ListView ruleView;
    private List<Map<String, Object>> datalist;
    private RuleViewAdapter adapter;
    private Toast Success;
    private Toast Failure;
    private Toast DeleteFail;
    private Toast timeOut_Toast;
    private SharedPreferences sp;
    private String username;
    private int RuleId;
    Map<String, Object> ruleinfo = new HashMap<String, Object>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_makerules, container, false);

        Success  = Toast.makeText(getActivity(),"成功",Toast.LENGTH_SHORT);
        Failure = Toast.makeText(getActivity(),"失败",Toast.LENGTH_SHORT);
        timeOut_Toast = Toast.makeText(getActivity(), "网络连接超时", Toast.LENGTH_SHORT);
        DeleteFail = Toast.makeText(getActivity(),"无法删除",Toast.LENGTH_SHORT);
        sp = getActivity().getSharedPreferences("parent", Context.MODE_PRIVATE);
        username = sp.getString("username","");
        ruleView = root.findViewById(R.id.rule_view);
        View emptyView = root.findViewById(R.id.empty);
        ruleView.setEmptyView(emptyView);
        datalist = getData();
        adapter = new RuleViewAdapter(getActivity(), datalist);
        ruleView.setAdapter(adapter);

        ruleView.setOnItemClickListener((parent, view, position, id) -> {
//            HashMap<String, Object> listinfo = (HashMap<String, Object>) ruleView.getItemAtPosition(position);//SimpleAdapter返回Map
//            //Log.d("onClick",listinfo.toString());
//            String listid ;//= listinfo.get("id").toString();
//            listid = "1";
//            Intent intent = new Intent();
//            //intent.setClass(getActivity(), RuleContentActivity.class);//this前面为当前activty名称，class前面为要跳转到得activity名称
//            intent.putExtra("listid", listid);
//            startActivity(intent);
//            getActivity().overridePendingTransition(R.anim.trans_in, R.anim.no_anim);
        });

        ruleView.setOnItemLongClickListener((parent, view, position, id) -> {
            ruleinfo = (Map<String, Object>) ruleView.getItemAtPosition(position);//SimpleAdapter返回Map
            RuleId = (int) ruleinfo.get("rule_id");
            String name = (String) ruleinfo.get("rule_name");
            final CommonDialog dialog = new CommonDialog(getActivity());
            dialog.setTitle("您确认要删除 " + name + " 吗？")
                    .setPositive("删除").setPositiveColor(Color.parseColor("#ff2d55"))
                    .setNegtive("取消")
                    .setMessage("删除后无法恢复.")
                    .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                        @Override
                        public void onPositiveClick() {
                            dialog.dismiss();
                            DeleteRulesThread deleteRulesThread = new DeleteRulesThread();
                            deleteRulesThread.start();
                            refresh();
                        }

                        @Override
                        public void onNegtiveClick() {
                            dialog.dismiss();
                        }
                    }).show();
            return true;
        });
        return root;
    }
    //从数据库获取数据
    public List<Map<String, Object>> getData() {
        datalist = new ArrayList<Map<String, Object>>();
        GetRulesThread getRulesThread = new GetRulesThread();
        getRulesThread.start();
        while(getRulesThread.isAlive());
        return datalist;
    }

    public class GetRulesThread extends Thread{
        public void run(){
            try {
                String json = "{\n" +
                        "  \"username\": \"" + username + "\"\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/rule/getByParUsername")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=JSONObject.parseObject(responseData);

                int code=(int)jsonObject.get("code");
                if(code == 100){
                    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                    JSONObject Rules;
                    for(int i=0;i<jsonArray.size();i++){
                        Rules = (JSONObject) jsonArray.get(i);
                        datalist.add(i,Rules);
                    }
                }
                else{
                    Failure.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    public class DeleteRulesThread extends Thread{
        public void run(){
            try {
                String json = "{\n" +
                        "  \"rule_id\": \"" + RuleId + "\"\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/rule/delete")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=JSONObject.parseObject(responseData);

                int code=(int)jsonObject.get("code");
                if(code == 100){
                    Success.show();
                }
                else if(code == -1){
                    DeleteFail.show();
                }
                else{
                    Failure.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        refresh();
    }

    //刷新listview
    public void refresh() {
        //刷新list
        datalist.clear();
        datalist = getData();
        adapter = new RuleViewAdapter(getActivity(), datalist);
        ruleView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    public static FragmentMakeRules newInstance() {
        return new FragmentMakeRules();
    }
}
